package com.wyg.learn.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @description:
 * @author: WYG
 * @time: 2020/10/10 9:47
 */

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;      //上下文
    private int result;  //  返回结果
    private String params;  //客户端调用方法时，传入参数

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;  //  其他方法会用到ctx
    }

    //收到服务器的数据后，调用方法
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        result = Integer.parseInt(msg.toString());
        notify();//唤醒等待线程
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    //被代理对象调用,发送数据给服务器,发送完成后等待被唤醒(wait->notify->return)
    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(params);
        wait();
        return result;  //服务方返回的结果
    }

    public void setParams(String params) {
        this.params = params;
    }
}
